package com.jx.common.xss;


import org.springframework.http.HttpMethod;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 防止XSS攻击的过滤器
 *
 * @author cecjx
 */
public class RespHeaderFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        System.out.println(req.getRequestURI());
        resp.setHeader("X-Content-Type-Options", "nosniff");
        // resp.setHeader("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-src 'self'; object-src 'none'; media-src 'self';");
        //不允许内联样式，内联脚本
        resp.setHeader("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-src 'self'; object-src 'none'; media-src 'self';");
        resp.setHeader("X-XSS-Protection", "1; mode=block");
        resp.setHeader("Strict-Transport-Security", "max-age=31536000");
        resp.setHeader("Referrer-Policy", "no-referrer");
        resp.setHeader("X-Permitted-Cross-Domain-Policies", "none");
        resp.setHeader("X-Download-Options", "noopen");
        resp.setHeader("X-Frame-Options", "DENY");
        resp.setHeader("Allow", "POST, GET");
        if (HttpMethod.GET.name().equalsIgnoreCase(req.getMethod())||HttpMethod.POST.name().equalsIgnoreCase(req.getMethod())) {
            chain.doFilter(request, response);
            return;
        }
        System.out.println("请求方式:"+req.getMethod()+"，请求地址:"+req.getRequestURI());
        // response.setContentType("text/html;charset=UTF-8");
        // resp.setHeader("Content-Type", "text/html;charset=UTF-8");
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }

    @Override
    public void destroy() {

    }
}
